package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyerCarBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyCarMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BuyCarServiceImpl implements IBuyCarService {
    @Autowired
    private IBuyCarMapper buyCarMapper;
    @Autowired
    private IProductMapper productMapper;
    @Override
    public void add(String option, ProductBean product, Integer num, Integer userId,Integer money) {
        if (option.equals("add")){
            productMapper.insert(product);
        }
        QueryWrapper<BuyerCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        qw.eq("fk_productId",product.getId());
        //查询指定用户ID和商品ID的购物信息
        BuyerCarBean buyerCarBean = buyCarMapper.selectOne(qw);
        if (buyerCarBean==null){//购物车中不存在该购物信息
            buyerCarBean =new BuyerCarBean();
            buyerCarBean.setUserId(userId);
            buyerCarBean.setProductId(product.getId());
            buyerCarBean.setNum(num);
            buyerCarBean.setBuyMoney(money);
            //保存购物信息
            buyCarMapper.insert(buyerCarBean);
        }
        else {//购物车中存在该购物信息，则更新数量
            buyerCarBean.setNum(buyerCarBean.getNum()+num);
            buyerCarBean.setBuyMoney(money);
            //修改购物数量
            buyCarMapper.updateById(buyerCarBean);
        }
    }

    @Override
    public void del(Integer buyCarId) {
        buyCarMapper.deleteById(buyCarId);
    }

    @Override
    public void updateNum(Integer buyCarId, Integer num) {
        BuyerCarBean buyerCarBean = buyCarMapper.selectById(buyCarId);
        buyerCarBean.setId(buyCarId);
        buyerCarBean.setNum(num);
        buyCarMapper.updateById(buyerCarBean);
    }

    @Override
    public List<BuyerCarBean> findByUserId(Integer userId) {

        return buyCarMapper.findByUserId(userId);
    }
}
